<template>
  <BaseLayout>
    <template #content>
      <div class="search-block">
        <el-form
          :inline="true"
          :model="queryParams"
        >
          <el-row :gutter="20">
            <el-col :span="3">
              <el-input
                v-model="queryParams.module"
                placeholder="操作模块"
                :suffix-icon="queryParams.module ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-input
                v-model="queryParams.userNickname"
                placeholder="用户昵称"
                :suffix-icon="queryParams.userNickname ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-select
                v-model="queryParams.type"
                placeholder="操作类型"
                clearable
                size="large"
              >
                <el-option
                  v-for="item in operateTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>

            <el-col :span="3">
              <el-select
                v-model="queryParams.result"
                placeholder="操作状态"
                clearable
                size="large"
              >
                <el-option
                  v-for="item in resultOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>

            <el-col :span="8">
              <el-date-picker
                v-model="queryParams.startTime"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="large"
              />
            </el-col>

            <el-col :span="2">
              <el-button
                type="primary"
                size="large"
                @click="getTableData"
              >
                搜索
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-table
        border
        v-loading="tableLoading"
        :data="tableData"
        :stripe="true"
        :header-cell-style="() => ({ background: '#F8F8F8' })"
      >
        <el-table-column
          prop="id"
          label="日志编号"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="module"
          label="操作模块"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="userNickname"
          label="用户昵称"
          min-width="120"
          align="center"
        />

        <el-table-column
          label="操作类型"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ formatOperateType(scope.row.type) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作状态"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.resultCode == 200 ? '成功' : '失败' }}
          </template>
        </el-table-column>

        <el-table-column
          prop="duration"
          label="执行时长（毫秒）"
          min-width="150"
          align="center"
        />

        <el-table-column
          label="操作时间"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            {{ formatTime(scope.row.startTime) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 详情弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        width="90%"
        @close="handleClose"
        align-center
      >
        <el-descriptions
          title="操作日志详情"
          border
        >
          <el-descriptions-item label="日志编号">
            {{ dialogForm.id }}
          </el-descriptions-item>

          <el-descriptions-item label="用户编号">
            {{ dialogForm.userId }}
          </el-descriptions-item>

          <el-descriptions-item label="用户昵称">
            {{ dialogForm.userNickname }}
          </el-descriptions-item>

          <el-descriptions-item label="操作模块">
            {{ dialogForm.module }}
          </el-descriptions-item>

          <el-descriptions-item label="操作名">
            {{ dialogForm.name }}
          </el-descriptions-item>

          <el-descriptions-item label="操作分类">
            {{ formatOperateType(dialogForm.type) }}
          </el-descriptions-item>

          <el-descriptions-item label="操作明细">
            {{ dialogForm.content }}
          </el-descriptions-item>

          <el-descriptions-item label="拓展字段">
            {{ dialogForm.exts }}
          </el-descriptions-item>

          <el-descriptions-item label="请求方法名">
            {{ dialogForm.requestMethod }}
          </el-descriptions-item>

          <el-descriptions-item label="请求地址">
            {{ dialogForm.requestUrl }}
          </el-descriptions-item>

          <el-descriptions-item label="用户 IP">
            {{ dialogForm.userIp }}
          </el-descriptions-item>

          <el-descriptions-item label="浏览器 UserAgent">
            {{ dialogForm.userAgent }}
          </el-descriptions-item>

          <el-descriptions-item label="Java 方法名">
            {{ dialogForm.javaMethod }}
          </el-descriptions-item>

          <el-descriptions-item label="Java 方法的参数">
            {{ dialogForm.javaMethodArgs }}
          </el-descriptions-item>

          <el-descriptions-item label="开始时间">
            {{ formatTime(dialogForm.startTime) }}
          </el-descriptions-item>

          <el-descriptions-item label="执行时长（毫秒）">
            {{ dialogForm.duration }}
          </el-descriptions-item>

          <el-descriptions-item label="结果码">
            {{ dialogForm.resultCode }}
          </el-descriptions-item>

          <el-descriptions-item label="结果提示">
            {{ dialogForm.resultMsg }}
          </el-descriptions-item>

          <el-descriptions-item label="结果数据">
            {{ dialogForm.resultData }}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </template>

    <template #footer>
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePagination"
      />
    </template>
  </BaseLayout>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { defaultPage, defaultPageSize } from '@/types/api.d'
import dayjs from 'dayjs'
import { operateTypeOptions, resultOptions } from '@/utils/globalOptions'
import BaseLayout from '@/layout/baseLayout/index.vue'
import { getSystemOperateLogPage } from '@/api/operateLog'
import { Search } from '@element-plus/icons-vue'

/**
 * 表格属性
 */
const tableData = ref([])
const tableLoading = ref(true)

/**
 * 详情弹窗属性
 */
const dialogVisible = ref(false)
const dialogForm = reactive({
  id: '',
  userId: '',
  userNickname: '',
  module: '',
  name: '',
  type: '',
  content: '',
  exts: '',
  requestMethod: '',
  requestUrl: '',
  userIp: '',
  userAgent: '',
  javaMethod: '',
  javaMethodArgs: '',
  startTime: '',
  duration: '',
  resultCode: '',
  resultMsg: '',
  resultData: ''
})

/**
 * 分页器属性
 */
const total = ref(0)

const queryParams = reactive({
  module: '', // 操作模块
  userNickname: '', // 用户昵称
  result: '', // 操作分类
  type: '', // 日志类型
  success: '', // 操作状态
  startTime: [], // 开始时间
  pageNo: defaultPage, // 当前页码
  pageSize: defaultPageSize // 每页显示数量
})

onMounted(async () => {
  await getTableData()
})

/**
 * 获取表格数据
 */
const getTableData = async () => {
  tableLoading.value = true
  const res = await getSystemOperateLogPage(queryParams)

  if (res) {
    tableData.value = res.list
    total.value = res.total
  }

  tableLoading.value = false
}

/**
 * 分页事件
 */
const handlePagination = async ({ page, limit }: { page: number; limit: number }) => {
  queryParams.pageNo = page
  queryParams.pageSize = limit
  await getTableData()
}

/**
 * 操作类型格式化
 */
const formatOperateType = (value: number | any) => {
  return operateTypeOptions.find(item => item.value == value)?.label
}

/**
 * 时间格式化
 */
const formatTime = (time: number | any) => {
  if (!time) {
    return '-'
  }

  return typeof time === 'number' ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
}

/**
 * 查看详情
 * @param data 详情数据
 */
const handleDetail = (data: any) => {
  console.log(data)
  // 将数据赋值给详情表单
  Object.keys(dialogForm).forEach(key => {
    dialogForm[key] = data[key]
  })
  dialogVisible.value = true
}

/**
 * 对话框关闭事件
 */
const handleClose = () => {
  Object.keys(dialogForm).forEach(key => {
    dialogForm[key] = ''
  })
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.search-block {
  margin-bottom: 20px;
}
</style>
